import functools
import json
import random
import string
import time
import requests

from app import db
from application.tools.comm import sendMsg
from captcha.image import ImageCaptcha
from flask import Blueprint, request, send_file, jsonify, redirect
from application.models.users.user import *
from application.tools.myjwt import mjwt
from application.tools.myredis import r

course_blue = Blueprint("courseblue", __name__)
# 添加课程使用， 获取标签， 分类， 类别
@course_blue.route("/getTags")
def getTags():
    tags = Tags.query.all()
    tagslist = [{"id": i.id,"name": i.name}for i in tags]
    types = Ctype.query.all()
    typeslist = [{"id": i.id, "name": i.name}for i in types]
    ctype = CourseType.query.all()
    ctypelist = [{"id": i.id, "name": i.name}for i in ctype]
    return jsonify({"code": 200, "tags": tagslist, "types": typeslist, "clist": ctypelist})

# 七牛云
@course_blue.route("/get_qntoken")
def get_qntoken():
    # -*- coding: utf-8 -*-
    # flake8: noqa
    from qiniu import Auth
    # 需要填写你的 Access Key 和 Secret Key
    access_key = 'PreRDw06bAO6l1rp3jYQ14emYXPu4YAz-kXxc7Im'
    secret_key = 'ImiyB_v7CH-QJgnc5cNbjRMCjx_mvm_dAtwEO0OM'
    # 构建鉴权对象
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'h2205a-ljy'
    # 3600为token过期时间，秒为单位。3600等于一小时
    token = q.upload_token(bucket_name)
    return jsonify({"code": 200, "token": token})
# 添加课程
@course_blue.route('/addCourse', methods=['POST'])
def addCourse():
    try:
        # 获取参数
        data = json.loads(request.data)
        # 校验参数是否获取
        if not data:
            return jsonify({"code": 400, "msg": "缺少参数"})
        # 写入课程表
        print(data['name'])
        course = Course(name=data.get('name'), url=data.get('url'), descrip=data.get('desc'), ctype=data.get("type"))
        db.session.add(course)
        # 获取新加的课程id
        scourse = Course.query.filter(Course.name == data['name']).first()

        # 写入课程标签
        for i in data['tags']:
            tag = Tags.query.filter(Tags.id==i).first()
            scourse.tags.append(tag)
            # sql = "insert into course_tag(courseid,tagid) values(%d,%d)"%(scourse.id, int(i))
            # db.session.execute(sql)

        # 课程分类表
        for i in data['ctype']:
            sql = "insert into course_cate(courseid,course_typeid) values(%d,%d)"%(scourse.id, int(i))
            db.session.execute(sql)
        db.session.commit()
        return jsonify({"code": 200, "msg": "添加成功"})
    except:
        db.session.rollback()
        return jsonify({"code": 400, "msg": "添加失败"})

import math
# @user_blue.route("/getCourse")
# def getCourse():
#     # 获取参数page
#     page = request.args.get("page")
#     # 获取已上线， 即将上线条件
#     online = int(request.args.get('is_publish'))
#     # 查询总条数
#     total = Course.query.filter(Course.is_publish == online).count()
#     # 定义每页显示多少条
#     page_size = 3
#     # 查询当前页记录
#     start = math.ceil((int(page)-1)*page_size)
#     # 获取排序字段
#     orderpara = request.args.get('orderpara')
#     print("orderpata=====", orderpara)
#     if orderpara == "new":
#         course = Course.query.order_by(Course.create_time.desc()).filter(Course.is_publish == online).offset(start).limit(page_size).all()
#     else:
#         course = Course.query.order_by(Course.views.desc()).filter(Course.is_publish == online).offset(start).limit(page_size).all()
#
#     # 获取过来的数据必须序列化
#     list = [{"id": i.id, "name": i.name, "url": i.url, "views": i.views} for i in course]
#     # 返回结果
#     return jsonify({"code": 200, "clist": list, "total": total, "page_size": page_size})




# # flask期末作业
# @user_blue.route("/student")
# def student():
#     # 获取参数page
#     page = request.args.get("page")
#     # 查询总条数
#     total = Student.query.count()
#     # 定义每页显示多少条
#     page_size = 2
#     # 查询当前页记录
#     start = math.ceil((int(page)-1)*page_size)
#     # 分页获取的数据
#     student = Student.query.offset(start).limit(page_size).all()
#     # 获取过来的数据必须序列化
#     list = [{"id": i.id, "name": i.name, "number": i.number} for i in student]
#     # 返回结果
#     return jsonify({"code": 200, "clist": list, "total": total, "page_size": page_size})

@course_blue.route('/getCourse', methods=['GET'])
def getCourse():
    # 获取当前页面
    page = request.args.get("page")
    # 获取已上线， 即将上线条件
    online = int(request.args.get('is_publish'))

    # 定义每页显示多少条
    page_size = 3
    # 获取条件
    start = math.ceil((int(page)-1)*page_size)
    # 获取类别
    types = int(request.args.get('types'))
    # 获取类别
    tags = int(request.args.get('tags'))
    # 排序字段
    orderpara = request.args.get('orderpara')
    # 重构where条件
    where = " 1=1"
    if online:
        where = where + " and c.is_publish="+str(online)

    if types > 0:
        where = where + " and c.ctype="+str(types)

    # 排序
    orderby = " order by c.views desc"
    if orderpara == "new":
        orderby = " order by c.create_time desc"
    # 查询一共有多少条
    if tags > 0:
        countsql = "select count(c.id) as tcount from course as c inner join course_tag as ct on c.id=ct.courseid where ct.tagid=" + str(tags)+" and"+where
    else:
        countsql = "select count(c.id) as tcount from course as c where"+where
    cres = db.session.execute(countsql)
    cdata = cres.fetchone()
    # 查询总条数
    total = cdata["tcount"]
    print(total)
    # 查询当前页对象
    if tags > 0:
        sql = "select c.* from course as c inner join course_tag as ct on c.id=ct.courseid where ct.tagid=" + str(tags) + " and " + where + orderby + " limit " + str(start) + "," + str(page_size)
    else:
        sql = "select c.* from course as c where " + where+orderby+" limit "+str(start)+","+str(page_size)
    res = db.session.execute(sql)
    data = res.fetchall()
    # 获取过来的数据必须序列化
    clist = [{"id": i.id, "name": i.name, "url": i.url, "views": i.views} for i in data]
    # 返回结果
    return jsonify({"code": 200, "clist": clist, "total": total, "page_size": page_size})

# 课程详情页面
@course_blue.route('/courseDetail', methods=['GET'])
def courseDetail():
    # 获取参数id
    course_id = request.args.get("cid")
    userid = request.args.get("userid")
    print("course_id: ", course_id)
    # 查询课程
    # sql = "SELECT * from course WHERE id="+str(course_id)
    # data = db.session.execute(sql)
    # cou = data.fetchall()
    cou = Course.query.filter(Course.id == course_id).first()
    print("cou======================", cou)
    # 判断用户是否登录
    if userid:
        key = "user" + str(userid) + "good" + str(course_id)
        r.hash_add(key, "id", cou.id)
        r.hash_add(key, "name", "商品"+str(cou.name))
        r.hash_add(key, "url", cou.url)
        print("添加成功")

    return jsonify({"code": 200, "cou": {
        "id": cou.id,
        "name": cou.name,
        "views": cou.views,
        "descrip": cou.descrip,
        "tcount": cou.tcount,
    }})


# 浏览记录
@course_blue.route('/getDetail', methods=['GET'])
def getDetail():
    # 接收参数
    userid = request.args.get('userid')
    findkey = "user" + str(userid) + "*"
    gidlist = r.getvalues(findkey)
    reslist = []
    for i in gidlist:
        goods = r.getall_hash(i)
        dict = {}
        for k, v in goods.items():
            kk = k.decode()
            vv = v.decode()
            dict[kk] = vv
        reslist.append(dict)
    print(reslist)
    return jsonify({"code": 200, "reslist": reslist})


# 加入购物车
@course_blue.route('/buy', methods=['GET'])
def buy():
    # 获取参数 userid  course
    userid = request.args.get('userid')
    course_id = request.args.get('course_id')
    # 加减类型
    type = 1
    try:
        type = request.args.get('type')
    except:
        pass
    # 从hash中获取数据 如果存在+1 buy1course
    key = "buy"+str(userid)+"course"+str(course_id)
    # 如果不存在存入redis hash
    flag = r.findkey_hash(key)
    if flag:
        # 数据+1
        ff = r.jiajian_hash(key, "number", 1, type)
        if ff == False:
            return jsonify({"code": 10010, "mes": "不能在减了"})
    else:
        r.hash_add(key, "id", course_id)
        r.hash_add(key, "number", 1)
    return jsonify({"code": 200})

# 获取购物车
@course_blue.route('/mycart', methods=['GET'])
def mycart():
    # 获取参数 userid
    userid = request.args.get('userid')
    # 从hash中获取商品id
    key = 'buy' + str(userid) + "*"
    goods = r.getvalues(key)
    glist = []
    tmoney = 0
    tcount = 0
    if goods:
        for i in goods:
            # 获取每一条商品的具体信息
            good = r.getall_hash(i)
            rescourse={}
            for k, v in good.items():
                params = k.decode()
                values = v.decode()
                print("k------------------------v", params, values)

                if params == "id":
                    # 获取到数据库商品信息
                    tcourse = Tcourse.query.filter(Tcourse.id == values).first()
                    rescourse["id"] = tcourse.id
                    rescourse["name"] = tcourse.title
                    rescourse["url"] = tcourse.url
                    rescourse["price"] = tcourse.price
                if params == "number":
                    # 获取到数据库商品数量
                    rescourse['number'] = values
            rescourse['total'] = int(rescourse['price']) * int(rescourse['number'])
            # 计算总价格
            tmoney = float(tmoney) + float(rescourse['total'])
            tcount = int(tcount) + int(rescourse['number'])
            glist.append(rescourse)
    # 价格，图片，名字。。。。。从mysql中获取， 从redsi商品缓存中读取
    # 数据重组返回
    return jsonify({"code": 200, "glist": glist, "tmoney": tmoney, "tcount": tcount})

# 获取训练营课程
@course_blue.route("/bootcamp")
def bootcamp():
    # 获取数据库存储的所有训练营课程
    trourse = Tcourse.query.all()
    clist = []
    # 序列化返回
    for i in trourse:
        clist.append({
            "id": i.id,
            "name": i.title,
            "url": i.url,
            "price": i.price,
            "store": i.store,
            "intro": i.intro
        })
    # 返回数据
    return jsonify({"code": 200, "clist": clist})